package com.onlyforfun.exchange;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.achartengine.GraphicalView;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.widget.ShareActionProvider;
import com.actionbarsherlock.widget.ShareActionProvider.OnShareTargetSelectedListener;
import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.onlyforfun.exchange.chart.HistoryPriceChart;
import com.onlyforfun.exchange.dao.BocExchangeDao;
import com.onlyforfun.exchange.dao.ExchangeDao;
import com.onlyforfun.exchange.dao.IcbcExchangeDao;
import com.onlyforfun.exchange.dao.SortKeeper;
import com.onlyforfun.exchange.domain.TimePrice;
import com.onlyforfun.exchange.listner.AdlistenerTracker;
import com.onlyforfun.exchange.util.EmptyViewUtils;
import com.onlyforfun.exchange.util.NetWorkUtil;

public class HistoryActivity extends AbstractActivity {

	private View mEmptyLoadingView = null;
    
    private LinearLayout contentView = null;
    private String currencyId;
    
    private AdView adView ;
    private HistoryPriceChart chart;
    private ExchangeDao exchangeDao;
    private static final String SHARED_FILE_NAME = "shared.png";
    
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == android.R.id.home) {
			this.finish();
		}
		return true;
	}
	 
//    private GestureDetector detector;  
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	setTheme(R.style.Theme_sherlock_light);
    	super.onCreate(savedInstanceState);
//    	requestWindowFeature(Window.FEATURE_PROGRESS);
//        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
//        setSupportProgress(Window.PROGRESS_END);
    	if (!NetWorkUtil.isOnline(getApplicationContext())) {
			Toast.makeText(this, R.string.non_connected, Toast.LENGTH_LONG).show();
			this.finish();
			return;
		}
    	getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    	
    	int bank = SortKeeper.readBank(getApplicationContext());
    	setTitle(getResources().getStringArray(R.array.banks)[bank]);
		if (bank == 0) {
			exchangeDao = new BocExchangeDao();
		} else {
			exchangeDao = new IcbcExchangeDao();
		}
		
//		Context context = getSupportActionBar().getThemedContext();
//        ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(context, R.array.banks, R.layout.sherlock_spinner_item);
//        list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
//        getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
//        getSupportActionBar().setListNavigationCallbacks(list, this);
//        getSupportActionBar().setSelectedNavigationItem(bank);
        
        setContentView(R.layout.history_activity);
	    contentView = (LinearLayout) findViewById(R.id.contentView);
        currencyId = getIntent().getStringExtra("currencyId");
        DownloadTimePriceTask priceTask = new DownloadTimePriceTask();
		priceTask.execute();
		showLoadingEmptyView();
		adView = (AdView)this.findViewById(R.id.adView);
	    adView.loadAd(new AdRequest());
	    adView.setAdListener(new AdlistenerTracker(getApplicationContext()));
    }

    //show loading view when init and loading data from network
    protected void showLoadingEmptyView() {
        if (mEmptyLoadingView == null) {
            mEmptyLoadingView = EmptyViewUtils.createLoadingView(this);
        }
        contentView.addView(mEmptyLoadingView);
    }
    
    @Override
	public void onDestroy() {
		super.onDestroy();
		contentView = null;
//		chart.getDownloadTaskManagerThread().setStop(true);
		chart = null;
		if (adView != null) {
			adView.destroy();
		}
	}

	private class DownloadTimePriceTask extends AsyncTask<Void, Void, List<TimePrice>> {
	    @Override
	    protected List<TimePrice> doInBackground(Void... date) {
	    	
	    	Calendar calendar = Calendar.getInstance();
			Date end = calendar.getTime();
			if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
				calendar.add(Calendar.DAY_OF_YEAR, -1);
			}
			if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
				calendar.add(Calendar.DAY_OF_YEAR, -1);
			}
			Date start = calendar.getTime();
			
	    	List<TimePrice> timePrices = new ArrayList<TimePrice>();
			timePrices.addAll(exchangeDao.findByCurrencyName(start, end, currencyId));
			while(timePrices.size() < 2) {
				calendar.add(Calendar.DAY_OF_YEAR, -1);
				start = calendar.getTime();
				timePrices.addAll(exchangeDao.findByCurrencyName(start, start, currencyId));
			}
			return timePrices;
	    }

	    @Override
	    protected void onPostExecute(List<TimePrice> timeprices) {
	    	chart = new HistoryPriceChart(HistoryActivity.this, currencyId, timeprices, exchangeDao);
	        GraphicalView gv = chart.execute();
	        if (contentView == null) {
	        	return;
	        }
	        contentView.removeAllViews();
	        contentView.addView(gv);
//	        setProgressBarVisibility(false);
	    }
	  }

//	@Override
//	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
//        DownloadTimePriceTask priceTask = new DownloadTimePriceTask();
//		priceTask.execute();
//		showLoadingEmptyView();
//		return true;
//	}
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate your menu.
        getSupportMenuInflater().inflate(R.menu.share_action_provider, menu);

        // Set file with share history to the provider and set the share intent.
        MenuItem actionItem = menu.findItem(R.id.menu_item_share_action_provider_action_bar);
        ShareActionProvider actionProvider = (ShareActionProvider) actionItem.getActionProvider();
        actionProvider.setOnShareTargetSelectedListener(new OnShareTargetSelectedListener() {
			
			@Override
			public boolean onShareTargetSelected(ShareActionProvider source,
					Intent intent) {
				Bitmap image = Bitmap.createBitmap(contentView.getWidth(), contentView.getHeight(), Bitmap.Config.RGB_565);
				contentView.draw(new Canvas(image));
				
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
                byte[] data;
            	image.compress(CompressFormat.PNG, 75, bos);
            	data = bos.toByteArray();
            	
            	FileOutputStream os = null;
				try {
					os = openFileOutput(SHARED_FILE_NAME,
					        Context.MODE_WORLD_READABLE);
					os.write(data, 0, data.length);
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
		            try {
		            	os.close();
		            } catch (IOException ioe) {
		               /* ignore */
		            }
		            try {
		            	bos.close();
		            } catch (IOException ioe) {
		               /* ignore */
		            }
		        }
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				Uri uri = Uri.fromFile(getFileStreamPath(SHARED_FILE_NAME));
				intent.getExtras().clear();
				intent.putExtra(Intent.EXTRA_STREAM, uri);
				intent.putExtra(Intent.EXTRA_TEXT, "\n" + getResources().getString(R.string.sharewith_tiles));
				getApplicationContext().startActivity(intent);
				return true;
			}
		});
        actionProvider.setShareHistoryFileName(ShareActionProvider.DEFAULT_SHARE_HISTORY_FILE_NAME);
        actionProvider.setShareIntent(createShareIntent());
        return true;
    }

    /**
     * Creates a sharing {@link Intent}.
     *
     * @return The sharing intent.
     */
    private Intent createShareIntent() {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("image/*");
        Uri uri = Uri.fromFile(getFileStreamPath("shared.png"));
        shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
        return shareIntent;
    }
}
